<template>
  <el-dialog
    v-model="showDialog"
    title="启用优惠券"
    width="1000px"
    :close-on-click-modal="false"
    destroy-on-close
    @opened="handleOpened"
    @closed="handleClosed"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="formRules"
    >
      <el-form-item prop="tableData">
        <el-table
          v-loading="loading"
          :data="form.tableData"
        >
          <el-table-column
            label="批次ID"
            prop="storeGoodsId"
            width="80"
          />
          <el-table-column
            label="批次名称"
            prop="name"
            width="120"
          />
          <el-table-column
            label="总库存/剩余库存"
            width="150"
          >
            <template #default="props">
              {{ props.row.totalStock }}/{{ props.row.stock }}
            </template>
          </el-table-column>
          <el-table-column
            label="可配置库存"
            width="150"
          >
            <template #default="props">
              {{ props.row.couponTotalNum - props.row.couponReceiveNum }}
            </template>
          </el-table-column>
          <el-table-column
            label="状态"
            width="100"
          >
            <template #default="scope">
              <el-switch
                v-model="scope.row.onlineStatus"
                inline-prompt
                :loading="scope.row.statusLoading_fe"
                :active-value="1"
                :inactive-value="0"
                active-text="上架"
                inactive-text="下架"
                @click="changeStatus(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="库存增减量">
            <template #default="props">
              <count-adjust
                v-model="props.row.addOrDeductionStockCount"
                show-symbol="+-"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="showDialog = false">
        取消
      </el-button>
      <el-button
        type="primary"
        @click="handleSubmit"
      >
        确定
      </el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import type { Ref } from "vue";
import type { ICouponManageRow, ICouponManageBatchRow, IStoreProductRow } from "@/api/modules/pointsMall";
import { ElMessage } from "element-plus";
import { switchProductStatus, getGoodsProducts, getCouponBatches, switchGoodsStatus } from "@/api/pointsMall";
import CountAdjust from "@/components/goodsCenter/common/CountAdjust.vue";


const props = withDefaults(
  defineProps<{
    show: boolean;
    row: ICouponManageRow; // 正在操作的优惠券行
    isEditOnlineStatus: boolean;
  }>(),
  {
    show: false,
    isEditOnlineStatus: false, //是否可以库存上下架
  }
);
const emits = defineEmits([ "update:show", "confirm", "cancel" ]);
const showDialog = computed({
  get() {
    return props.show;
  },
  set(val) {
    return emits("update:show", val);
  },
});

const formRef = ref()
const formRules = ref({
  tableData: {
    required: true,
    validator: (rule: any, val: any, callback: any) => {
      let verifyFlag = 1;
      for (let i = 0; i < form.value.tableData.length; i++) {
        const row = form.value.tableData[i];
        const _addOrDeductionStockCount = row.addOrDeductionStockCount
        const remainStock = row.couponTotalNum - row.couponReceiveNum // 可配置库存
        if (!isEmpty(row.addOrDeductionStockCount)) {
          // 填写了库存增减量
          if (_addOrDeductionStockCount > 0 && _addOrDeductionStockCount > (remainStock - row.stock)) {
            callback(new Error(`【第${i + 1}行】批次的库存【增】量不能大于可配置库存`));
            verifyFlag = 0
            break;
          }
        
          if (_addOrDeductionStockCount < 0 && Math.abs(_addOrDeductionStockCount) > row.stock) {
            callback(new Error(`【第${i + 1}行】规格的库存【减】量不能大于剩余库存`));
            verifyFlag = 0
            break;
          }
        }

      }

      if (!verifyFlag) {
        return
      }

      callback();
    }
  }
})
const form = ref({
  tableData: []
})

const isEmpty = (val: any) => {
  return val === undefined || val === null || val === ''
}

const handleSubmit =  () => {
  formRef.value?.validate(async (valid: boolean) => {
    if (!valid) {
      return
    }

    let targetProduct = form.value.tableData.find((item) => item.onlineStatus == 1)
    if (!targetProduct) {
      ElMessage.error("启用优惠券，需启用至少一个批次");
      return
    }

    targetProduct = form.value.tableData.find((item) => (item.stock > 0 || item.addOrDeductionStockCount > 0))
    if (!targetProduct) {
      ElMessage.error("启用优惠券，至少应有一个批次库存不为0");
      return
    }

    targetProduct = form.value.tableData.find((item) => (item.stock + item.addOrDeductionStockCount) <= (item.couponTotalNum - item.couponReceiveNum))
    if (!targetProduct) {
      ElMessage.error("剩余库存 + 库存增减量 需小于 可配置库存");
      return
    }

    const rs = await switchGoodsStatus({
      id: props.row.id,
      name: props.row.name,
      onlineStatus: 1,
      spes: form.value.tableData.map((item) => ({
        id: item.id,
        onlineStatus: item.onlineStatus,
        type: item.addOrDeductionStockCount > 0 ? 1 : 2,
        stock: Math.abs(item.addOrDeductionStockCount),
      })),
    });

    if (rs.code === 200) {
      ElMessage.success("更新成功")
      showDialog.value = false;
      emits("confirm");
    }
  })
};

//单个规格上下架
const changeStatus = async (row: ICouponManageBatchRow) => {
  const data = {
    name: row.name,
    id: row.id,
  };
  const res = await switchProductStatus(data);

  if (res.code === 200) {
    _getTableData();
    ElMessage.success("操作成功");
  }
};

const goodsProducts:Ref<IStoreProductRow[]> = ref([])
const _getGoodsProducts = async () => {
  const rs = await getGoodsProducts({
    id: props.row.id
  })
  if (rs.code === 200) {
    goodsProducts.value = rs.payload ?? []
  }
}

const couponBatches:Ref<ICouponManageBatchRow> = ref([])
const _getCouponBatches = async () => {
  const rs = await getCouponBatches({
    id: props.row.storeGoodsId
  })

  if (rs.code === 200) {
    couponBatches.value = rs.payload ?? []
  }
}

// const tableData = ref([])
const _getTableData = async () => {
  await _getGoodsProducts()
  await _getCouponBatches()

  form.value.tableData = goodsProducts.value.map(item => {
    const matchedBatchItem = couponBatches.value.find(batchItem => batchItem.couponDefineId === item.storeGoodsId)
    
    return {
      ...item,
      couponTotalNum: matchedBatchItem.couponTotalNum,
      couponReceiveNum: matchedBatchItem.couponReceiveNum
    }
  })
}

const handleOpened = async () => {
  _getTableData();
};

const handleClosed = () => {

};
</script>

<style scoped lang="scss"></style>
